package org.example.backend.service;

import org.example.backend.entity.PolicyInfo;
import org.example.backend.mapper.PolicyInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class FileService {
    @Autowired
    private PolicyInfoMapper policyInfoMapper;

    // 通过政策id下载政策正文为txt文件（参数类型改为String，正文取最细分地址）
    public ResponseEntity<?> downloadPolicyTextById(String policyId) {
        PolicyInfo policy = policyInfoMapper.selectById(policyId);
        if (policy == null) {
            return ResponseEntity.status(404).body("政策id不存在");
        }
        String filename = "policy_" + policyId + ".txt";
        String content = getMostDetailedContent(policy);
        if (content == null) content = "";
        byte[] fileBytes = content.getBytes(StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .contentType(MediaType.TEXT_PLAIN)
                .body(fileBytes);
    }

    // 工具方法：获取政策正文（优先mainText字段）
    private String getMostDetailedContent(PolicyInfo policy) {
        if (policy == null) return "";
        if (policy.getMainText() != null && !policy.getMainText().isEmpty()) return policy.getMainText();
        return "";
    }
}
